

#include<opencv2/opencv.hpp>
#include<vlc/vlc.h>

#include <sys/time.h>
#include <unistd.h>

using namespace std;
using namespace cv;

class FooC {
public:
    FooC() {

    }

    ~FooC() {

    }

    void FooP() {
        std::cout << "This Foo" << std::endl;
    }
};

unsigned int width = 2560;
unsigned int height = 1440;
//unsigned int width = 640;
//unsigned int height = 480;
static char *videobuf;

libvlc_instance_t *instance = NULL;
libvlc_media_t *media = NULL;
libvlc_media_player_t *media_player = NULL;

void *lock(void *data, void **p_pixels) {
    *p_pixels = videobuf;
    return NULL;
}

void display(void *data, void *id) {
//    IplImage *img = cvCreateImage(CvSize(width, height), IPL_DEPTH_8U, 4);
//    img->imageData = videobuf;
//    //imshow("test", cvarrToMat(img));
//    cvShowImage("test", img);
//    waitKey(10);
//    cvReleaseImage(&img);

    ((FooC *) data)->FooP();

    Mat im = Mat(height, width, CV_8UC4);
    im.data = (uchar *) videobuf;

    std::cout << "time" << std::endl;
//    cv::namedWindow("CaptureOnePicture2Mem",cv::WINDOW_NORMAL);
//    cv::imshow("CaptureOnePicture2Mem", im);
//    cv::resizeWindow("CaptureOnePicture2Mem",1280,800);
//    cv::waitKey(1);


    struct timeval t;
    gettimeofday(&t, NULL);
//    imwrite(std::to_string(t.tv_sec) + "." + std::to_string(t.tv_usec) + "_stream.jpg", im);


}

void unlock(void *data, void *id, void *const *p_pixels) {
    (void) data;
    assert(id == NULL);
    std::cout << "time2" << std::endl;

}


int main() {
    FooC foo;

    videobuf = (char *) malloc((width * height) << 2);

    memset(videobuf, 0, (width * height) << 2);

    const char *vlc_args[] = {
            "--ignore-config", "--network-caching=500", "--rtsp-tcp", "--vout=vdummy"            // 不产生播放窗口
            , "--no-osd"                 // 不显示字幕
            , "--no-snapshot-preview"    // 不做截图预览

    };
    instance = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
//    instance = libvlc_new(0, NULL);

//    media = libvlc_media_new_location(instance, "rtsp://182.145.195.237:8099/DevAor=51000000001317000031");
    media = libvlc_media_new_location(instance,
                                      "rtsp://admin:cdzs123456@192.168.1.180:554/cam/realmonitor?channel=1&subtype=0");

    media_player = libvlc_media_player_new_from_media(media);
    libvlc_media_release(media);

    libvlc_video_set_callbacks(media_player, lock, unlock, display, &foo);
    libvlc_video_set_format(media_player, "RV32", width, height, width << 2);

    int resultStatus = -1;
    resultStatus = libvlc_video_get_size(media_player, 100, &width, &height);
    std::cout << " RET: " << resultStatus << " W: " << width << " H: " << height << std::endl;

    libvlc_media_player_play(media_player);

    while (1) {
        sleep(1);
    }
    return 0;
}


